package com.xiaomaoguai.fcp.pre.kepler.router.rpc.server.servlet.response;

import com.xiaomaoguai.fcp.pre.kepler.router.rpc.server.servlet.request.NettyHttpServletRequest;
import com.xiaomaoguai.fcp.pre.kepler.router.utils.SerializeUtils;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;

import java.io.IOException;

public class SendResponse {

	public static NettyHttpServletResponse crateResponse(NettyHttpServletRequest servletRequest, HttpResponseStatus status, boolean keepAlive) {
		DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, false);
		HttpUtil.setKeepAlive(response, keepAlive);
		return new NettyHttpServletResponse(servletRequest, response);
	}

	public static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) throws IOException {
		resp(ctx, crateResponse(status, false), SerializeUtils.encode(null));
	}

	public static void resp(ChannelHandlerContext ctx, NettyHttpServletResponse response, byte[] content) throws IOException {
		response.getOutputStream().write(content);
		response.setContentLength(content.length);
		resp(ctx, response);
	}

	public static NettyHttpServletResponse crateResponse(HttpResponseStatus status, boolean keepAlive) {
		DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, false);
		HttpUtil.setKeepAlive(response, keepAlive);
		return new NettyHttpServletResponse(null, response);
	}

	public static void resp(ChannelHandlerContext ctx, NettyHttpServletResponse response) {
		FullHttpResponse fullHttpResponse = response.getNettyResponse();
		ChannelFuture future = ctx.writeAndFlush(fullHttpResponse);
		if (!HttpUtil.isKeepAlive(fullHttpResponse)) {
			future.addListener(ChannelFutureListener.CLOSE);// 如果不是keep-alive，写完后关闭channel
		}
	}
}
